let fs = require('fs');
let url = require('url');
var log = require('./logs').logs;

function freamtJSONData(request, query) {
  return new Promise((s, f) => {
    let postData = "";
    let JSONData = "";
    request.addListener('data', function(pos) {
      postData += pos;
    });
    request.addListener('end', function() {
      log.info('数据接受完成');
      JSONData = query.parse(postData);
      if (!JSONData.file || !JSONData.path) {
        JSONData = JSON.parse(postData);
      }
      s(JSONData);
    })
  });
}

function index(request, response, query) {
  'use strict';
  if (query.file && query.path) {
    let url = './file/' + query.path + '/' + query.file + '.json';
    fs.exists(url, function(ss) {
      if (ss) {
        fs.readFile(url, 'utf8', function(error, data) {
          if (error) {
            response.writeHead(200, {
              "Content-Type": "application/json",
              "Access-Control-Allow-Origin": "*",
              "Access-Control-Allow-Methods": "GET",
              "Access-Control-Allow-Headers": "x-requested-with,content-type,token,deviceid,apptype,devicetype,appversion"

            });
            response.write('读取文件错误');
            response.end();
            log.info('读取文件错误');
            return
          }
          if (query.timeout) {
            let timeout = parseInt(query.timeout) * 1000;
            setTimeout(function() {
              response.writeHead(200, {
                "Content-Type": "application/json",
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Methods": "GET",
                "Access-Control-Allow-Headers": "x-requested-with,content-type,token,deviceid,apptype,devicetype,appversion"
              });
              response.write(data);
              response.end();
              log.info('延时' + query.timeout + 's,读取成功');
              log.info(data);
              log.info('======== END ========');
            }, timeout)
            return
          }
          response.writeHead(200, {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "GET",
            "Access-Control-Allow-Headers": "x-requested-with,content-type,token,deviceid,apptype,devicetype,appversion"
          });
          response.write(data);
          response.end();
          log.info('读取成功');
          log.info(data);
          log.info('======== END ========');
        });
      } else {
        response.writeHead(200, {
          "Content-Type": "application/json",
          "Access-Control-Allow-Origin": "*",
          "Access-Control-Allow-Methods": "GET",
          "Access-Control-Allow-Headers": "x-requested-with,content-type,token,deviceid,apptype,devicetype,appversion"
        });
        response.write('没有找到文件请确认');
        log.info('没有找到文件请确认');
        response.end();
      }
    });
  } else {
    response.writeHead(200, {
      "Content-Type": "application/json",
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "GET",
      "Access-Control-Allow-Headers": "x-requested-with,content-type,token,deviceid,apptype,devicetype,appversion"
    });
    response.write('参数错误请验证');
    response.end();
    log.info('参数错误请验证');
  }
  log.info('已响应 => index =>' + query.path + '/' + query.file + '.json');
}

async function postGetData(request, response, query) {
  let reqData = await freamtJSONData(request, query);
  log.debug('获取到的数据为');
  console.log(reqData);
  'use strict';
  if (reqData.file && reqData.path) {
    let url = './file/' + reqData.path + '/' + reqData.file + '.json';
    fs.exists(url, function(ss) {
      if (ss) {
        fs.readFile(url, 'utf8', function(error, data) {
          if (error) {
            response.writeHead(200, {
              "Content-Type": "application/json",
              "Access-Control-Allow-Origin": "*",
              "Access-Control-Allow-Methods": "POST",
              "Access-Control-Allow-Headers": "x-requested-with,content-type,token,deviceid,apptype,devicetype,appversion"

            });
            response.write('读取文件错误');
            response.end();
            log.info('读取文件错误');
            return
          }
          if (reqData.timeout) {
            console.log(data.timeout);
            let timeout = parseInt(reqData.timeout) * 1000;
            setTimeout(function() {
              response.writeHead(200, {
                "Content-Type": "application/json",
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Methods": "POST",
                "Access-Control-Allow-Headers": "x-requested-with,content-type,token,deviceid,apptype,devicetype,appversion"
              });
              response.write(data);
              response.end();
              log.info('延时' + reqData.timeout + 's,读取成功');
              log.info(data);
              log.info('======== END ========');
            }, timeout)
            return
          }
          response.writeHead(200, {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "POST",
            "Access-Control-Allow-Headers": "x-requested-with,content-type,token,deviceid,apptype,devicetype,appversion"
          });
          response.write(data);
          response.end();
          log.info('读取成功');
          log.info(data);
          log.info('======== END ========');
        });
      } else {
        response.writeHead(200, {
          "Content-Type": "application/json",
          "Access-Control-Allow-Origin": "*",
          "Access-Control-Allow-Methods": "POST",
          "Access-Control-Allow-Headers": "x-requested-with,content-type,token,deviceid,apptype,devicetype,appversion"
        });
        response.write('没有找到文件请确认');
        log.info('没有找到文件请确认');
        response.end();
      }
    });
  } else {
    if (reqData.timeout) {
      console.log(reqData.timeout);
      let timeout = parseInt(reqData.timeout) * 1000;
      setTimeout(function() {
        response.writeHead(200, {
          "Content-Type": "application/json",
          "Access-Control-Allow-Origin": "*",
          "Access-Control-Allow-Methods": "POST",
          "Access-Control-Allow-Headers": "x-requested-with,content-type,token,deviceid,apptype,devicetype,appversion"
        });
        response.write('没有找到文件请确认');
        log.info('没有找到文件请确认');
        response.end();
      }, timeout)
      return
    }
    response.writeHead(200, {
      "Content-Type": "application/json",
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "POST",
      "Access-Control-Allow-Headers": "x-requested-with,content-type,token,deviceid,apptype,devicetype,appversion"
    });
    response.write('参数错误请验证');
    response.end();
    log.info('参数错误请验证');
  }
}

function file(request, response, query) {
  'use strict';
  let postData = '';
  request.addListener('data', function(postDataChunk) {
    postData += postDataChunk;
  });
  request.addListener('end', function() {
    log.info('数据接收完成');
    if (postData) {
      let params = query.parse(postData);
      if (!params.name) {
        params = JSON.parse(postData);
      }
      log.info(postData);
      log.info(params);
      if (params && params.name && params.data) {
        log.info('开始存储');
        let path = './file/' + params.path;
        let url = './file/' + params.path + '/' + params.name + '.json';
        log.info(params.data);
        fs.exists(path, function(exists) {
          if (!exists) {
            response.writeHead(501, {
              "Content-Type": "application/json",
              "Access-Control-Allow-Origin": "*",
              "Access-Control-Allow-Methods": "POST",
              "Access-Control-Allow-Headers": "x-requested-with,content-type"
            });
            response.write('文件夹信息错误');
            response.end();
          }
        });
        fs.writeFile(url, params.data, function(err, data) {
          if (err) {
            log.info(err);
            response.writeHead(501, {
              "Content-Type": "application/json",
              "Access-Control-Allow-Origin": "*",
              "Access-Control-Allow-Methods": "POST",
              "Access-Control-Allow-Headers": "x-requested-with,content-type"
            });
            response.write('服务器错误');
            response.end();
            return;
          }
          response.writeHead(200, {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "POST",
            "Access-Control-Allow-Headers": "x-requested-with,content-type"
          });
          response.write('success');
          response.end();
        });
      } else {
        response.writeHead(500, {
          "Content-Type": "application/json",
          "Access-Control-Allow-Origin": "*",
          "Access-Control-Allow-Methods": "POST",
          "Access-Control-Allow-Headers": "x-requested-with,content-type"
        });
        response.write("数据解析错误, 请确认");
        response.end();
      }
    } else {
      response.writeHead(200, {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "POST",
        "Access-Control-Allow-Headers": "x-requested-with,content-type"
      });
      response.write('No Data');
      response.end();
    }
  });
}

function formPost(request, response, query) {
  'use strict';
  let postData = '',
    params,
    num = 0,
    filename = 'dafeultForm' + num,
    url = './file/' + filename + '.json';
  request.addListener('data', function(postDataChunk) {
    postData += postDataChunk;
  });
  request.addListener('end', function() {
    log.info('form => over');
    if (postData) {
      params = query.parse(postData);
      params = JSON.stringify(params);
      fs.writeFile(url, params, function(err, data) {
        if (err) {
          log.info(err);
          response.writeHead(501, {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "POST",
            "Access-Control-Allow-Headers": "x-requested-with,content-type"
          });
          response.write('服务器错误');
          response.end();
          return;
        }
        response.writeHead(200, {
          "Content-Type": "application/json",
          "Access-Control-Allow-Origin": "*",
          "Access-Control-Allow-Methods": "POST",
          "Access-Control-Allow-Headers": "x-requested-with,content-type"
        });
        response.write("ok" + filename);
        response.end();
        num++;
      });
    } else {
      response.writeHead(200, {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "POST",
        "Access-Control-Allow-Headers": "x-requested-with,content-type"
      });
      response.write('No Data');
      response.end();
    }
  });
}

function time(request, response, query) {
  let a = Math.random();
  a > 0.5 ? a = 'ok' : a = 'err'
  setTimeout(function() {
    response.writeHead(200, {
      "Content-Type": "application/json",
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "POST",
      "Access-Control-Allow-Headers": "x-requested-with,content-type"
    });
    response.write(a);
    response.end();
  }, 2000);
}

function pawd(request, response, query) {
  'use strict';
  let url = './file/newapi/password.json';
  let postData = "";
  let params;
  let postdas;
  request.addListener('data', function(postDataChunk) {
    postData += postDataChunk;
  });
  request.addListener('end', function() {
    if (postData) {
      params = query.parse(postData);
      if (!params.username) {
        params = JSON.parse(postData);
      }
      if (params.username && !params.pwd && !params.name) {
        fs.readFile(url, 'utf8', function(error, data) {
          if (error) console.error(error);
          data = JSON.parse(data);
          response.writeHead(200, {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "POST",
            "Access-Control-Allow-Headers": "x-requested-with,content-type"
          });
          if (data[params.username]) {
            response.write('false');
          } else {
            response.write('true');
          }
          response.end();
        });
      } else {
        fs.readFile(url, 'utf8', function(error, data) {
          if (error) {
            console.error(error);
            response.writeHead(501, {
              "Content-Type": "application/json",
              "Access-Control-Allow-Origin": "*",
              "Access-Control-Allow-Methods": "POST",
              "Access-Control-Allow-Headers": "x-requested-with,content-type"
            });
            response.write('服务器错误');
            response.end();
            return;
          }
          data = JSON.parse(data);
          data[params.username] = {}
          data[params.username].pwd = params.pwd;
          data[params.username].name = params.name;
          data[params.username].sectiID = md5('cander' + Math.random());
          postdas = JSON.stringify(data);
          fs.writeFile(url, postdas, function(error, data) {
            if (error) {
              log.info(error);
              response.writeHead(501, {
                "Content-Type": "application/json",
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Methods": "POST",
                "Access-Control-Allow-Headers": "x-requested-with,content-type"
              });
              response.write('服务器错误');
              response.end();
              return;
            }
            response.writeHead(200, {
              "Content-Type": "application/json",
              "Access-Control-Allow-Origin": "*",
              "Access-Control-Allow-Methods": "POST",
              "Access-Control-Allow-Headers": "x-requested-with,content-type"
            });
            response.write("success");
            response.end();
          })
        });
      }

    } else {
      response.writeHead(200, {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "POST",
        "Access-Control-Allow-Headers": "x-requested-with,content-type"
      });
      response.write('No Data');
      response.end();
    }
  })
}

function login(request, response, query) {
  'use strict';
  let url = './file/newapi/password.json';
  let postData = "";
  let params;
  let receiptObj = {
    resultCode: '0000', // '0000 => 没有找到数据 / 0001 => 没有注册 / 0002 => 密码错误 / 0200 => 成功'
    USERNAME: '',
    userID: ''
  }
  let receipt = "";
  request.addListener('data', function(postDataChunk) {
    postData += postDataChunk;
  });
  request.addListener('end', function() {
    if (postData) {
      params = query.parse(postData);
      if (!params.username || !params.pwd) {
        params = JSON.parse(postData);
      }
      fs.exists(url, function(ss) {
        if (ss) {
          fs.readFile(url, 'utf8', function(error, data) {
            data = JSON.parse(data);
            if (!data[params.username]) {
              receiptObj.resultCode = '0001';
              receiptObj.USERNAME = '';
            } else if (params.pwd !== data[params.username].pwd) {
              receiptObj.resultCode = '0002';
              receiptObj.name = '';
            } else {
              receiptObj.resultCode = '0200';
              receiptObj.USERNAME = data[params.username].name;
              receiptObj.userID = data[params.username].sectiID;
            }
            receipt = JSON.stringify(receiptObj);
            response.writeHead(200, {
              "Content-Type": "application/json",
              "Access-Control-Allow-Origin": "*",
              "Access-Control-Allow-Methods": "GET",
              "Access-Control-Allow-Headers": "x-requested-with,content-type"
            });
            response.write(receipt);
            response.end();
          });
        } else {
          response.writeHead(200, {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "GET",
            "Access-Control-Allow-Headers": "x-requested-with,content-type"
          });
          receiptObj.resultCode = '0000';
          receiptObj.USERNAME = '';
          receipt = JSON.stringify(receiptObj)
          response.write(receipt);
          response.end();
        }
      });
    } else {
      response.writeHead(200, {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "POST",
        "Access-Control-Allow-Headers": "x-requested-with,content-type"
      });
      response.write('No Data');
      response.end();
    }
  })
}

function md5(data) {
  let Buffer = require("buffer").Buffer;
  let buf = new Buffer(data);
  let str = buf.toString("binary");
  let crypto = require("crypto");
  return crypto.createHash("md5WithRSAEncryption").update(str).digest("hex");
}

function test(equest, response, query){
  response.writeHead(404, {
              "Content-Type": "text/javascript",
              });
            response.write('typeof json1==="function"&&json1({code:0})');
            response.end();
}

exports.index = index;
exports.file = file;
exports.form = formPost;
exports.time = time;
exports.pawd = pawd;
exports.login = login;
exports.postGetData = postGetData;
exports.test = test;




